package com.yst.web.common;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.List;

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> implements Serializable {
    /**
     * code of the result
     */
    private int code;
    /**
     * data of the result
     */
    private T data;
    /**
     * message of the result
     */
    private String msg;

    public Result(T data){
        if (data instanceof Throwable) {
            if (data instanceof RuntimeException){
                setCode(ResultCode.ERROR_BUSINESS);
                setMsg(((RuntimeException)data).getMessage());
            }
            else
            {
                setCode(ResultCode.ERROR_UNKNOWN);
            }
        }
        else {
            this.data = data;
            setCode(ResultCode.SUCCESS);
        }
    }

    public Result<T> setCode(ResultCode code){
        this.code=code.code;
        this.msg=code.description;
        return this;
    }

    public Result<T> setCode(int code){
        this.code=code;
        return this;
    }

    public <D extends Serializable> D dataTo(Class<? extends D> clazz){
        return JSON.parseObject(data.toString(),clazz);
    }

    public <D> List<D> dataToArray(Class<D> clazz){
        return JSON.parseArray(data.toString(),clazz);
    }

    public static <T> Result<T> from(RuntimeException exception){
        return new Result<T>().setCode(ResultCode.ERROR_BUSINESS)
                .setMsg(exception.getMessage());
    }

    public static <T> Result<T> from(Exception exception){
        if (exception instanceof RuntimeException){
            return from((RuntimeException) exception);
        }
        return new Result<T>().setCode(ResultCode.ERROR_UNKNOWN);
    }

}
